package com.ctshk.rpc.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.NumberConstant;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.system.dto.MainDataAirAirportDTO;
import com.ctshk.rpc.system.entity.MainDataAirAirport;
import com.ctshk.rpc.system.entity.SysArea;
import com.ctshk.rpc.system.mapper.MainDataAirAirportMapper;
import com.ctshk.rpc.system.mapper.SysAreaMapper;
import com.ctshk.rpc.system.req.MainDataAirAirportAddReq;
import com.ctshk.rpc.system.req.MainDataAirAirportListReq;
import com.ctshk.rpc.system.req.MainDataAirAirportUpdateReq;
import com.ctshk.rpc.system.service.IMainDataAirAirportService;
import com.github.houbb.heaven.util.util.CollectionUtil;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.FileInputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *   城市-机场-主数据服务实现类
 * </p>
 *
 * @author lihang
 * @since 2021-03-18
 */
@DubboService
public class MainDataAirAirportServiceImpl extends ServiceImpl<MainDataAirAirportMapper, MainDataAirAirport> implements IMainDataAirAirportService {

    @Autowired
    private MainDataAirAirportMapper mainDataAirAirportMapper;

    @Autowired
    private SysAreaMapper sysAreaMapper;

    @Override
    public Result add(MainDataAirAirportAddReq req, TokenUser tokenUser) {
        /**判断数据是否重复 国家id 城市id 机场三字码*/
        QueryWrapper<MainDataAirAirport> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MainDataAirAirport::getCustomId,req.getCustomId());
        queryWrapper.lambda().eq(MainDataAirAirport::getAirportCode,req.getAirportCode());
        List<MainDataAirAirport> mainDataAirAirportList = mainDataAirAirportMapper.selectList(queryWrapper);
        if(CollectionUtil.isNotEmpty(mainDataAirAirportList)){
            return  Result.failed(SystemError.SYS_421);
        }
        MainDataAirAirport mainDataAirAirport = EntityUtil.copy(req,MainDataAirAirport.class);
        Long id = IdWorker.getId();
        mainDataAirAirport.setId(id);
        mainDataAirAirport.setGmtCreate(LocalDateTime.now());
        mainDataAirAirport.setCreatorId(tokenUser.getId()+"");
        mainDataAirAirport.setGmtModified(LocalDateTime.now());
        mainDataAirAirport.setModifiedId(tokenUser.getId());
        mainDataAirAirport.setModifiedName(tokenUser.getUsername());
        mainDataAirAirport.setCreatorName(tokenUser.getUsername());
        mainDataAirAirport.setVersion(1);
        mainDataAirAirportMapper.insert(mainDataAirAirport);
        return Result.success(id);
    }

    @Override
    public Result<PageResponse<MainDataAirAirportDTO>> list(MainDataAirAirportListReq req) {
        Page<MainDataAirAirport> page = new Page<>(req.getPageNo(), req.getPageSize());
        QueryWrapper<MainDataAirAirport> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ObjectUtils.isNotEmpty(req.getCustomId()),MainDataAirAirport::getCustomId,req.getCustomId());
        queryWrapper.lambda().eq(StringUtils.isNotBlank(req.getAirportCode()),MainDataAirAirport::getAirportCode,req.getAirportCode());
        queryWrapper.lambda().like(StringUtils.isNotBlank(req.getAirportName()),MainDataAirAirport::getAirportName,req.getAirportName());
        IPage<MainDataAirAirport> iPage = mainDataAirAirportMapper.selectPage(page,queryWrapper);
        if(CollectionUtil.isEmpty(iPage.getRecords())){
            return   Result.success(new PageResponse<MainDataAirAirportDTO>(new ArrayList<>(), iPage.getCurrent() == 1,iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize()));
        }
        List<MainDataAirAirportDTO> mainDataAirAirportListDTOS = EntityUtil.copyList(iPage.getRecords(), MainDataAirAirportDTO.class);
        return   Result.success(new PageResponse<MainDataAirAirportDTO>(mainDataAirAirportListDTOS, iPage.getCurrent() == 1,iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize()));
    }

    @Override
    public Result<MainDataAirAirportDTO> info(Long id) {
        MainDataAirAirport mainDataAirAirport = mainDataAirAirportMapper.selectById(id);
        if(null==mainDataAirAirport){
            return  Result.failed(SystemError.SYS_411);
        }
        MainDataAirAirportDTO mainDataAirAirportDTO = EntityUtil.copy(mainDataAirAirport,MainDataAirAirportDTO.class);
        return Result.success(mainDataAirAirportDTO);
    }

    @Override
    public Result updateStatus(Long id, TokenUser currentUser) {
        MainDataAirAirport mainDataAirAirport = mainDataAirAirportMapper.selectById(id);
        if(null==mainDataAirAirport){
            return  Result.failed(SystemError.SYS_411);
        }
        UpdateWrapper<MainDataAirAirport> updateWrapper = new UpdateWrapper();
        updateWrapper.lambda().eq(MainDataAirAirport::getId,id);
        if(mainDataAirAirport.getStatus().intValue()== NumberConstant.ONE.getValue().intValue()){
            updateWrapper.lambda().set(MainDataAirAirport::getStatus,NumberConstant.ZERO.getValue());
        }else{
            updateWrapper.lambda().set(MainDataAirAirport::getStatus,NumberConstant.ONE.getValue());
        }
        updateWrapper.lambda().set(MainDataAirAirport::getModifiedId, currentUser.getId());
        updateWrapper.lambda().set(MainDataAirAirport::getModifiedName, currentUser.getUsername());
        updateWrapper.lambda().set(MainDataAirAirport::getGmtModified, LocalDateTime.now());
        mainDataAirAirportMapper.update(null,updateWrapper);
        return Result.success(id);
    }

    @Override
    public Result update(MainDataAirAirportUpdateReq req, TokenUser tokenUser) {
        QueryWrapper<MainDataAirAirport> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MainDataAirAirport::getCustomId,req.getCustomId());
        queryWrapper.lambda().eq(MainDataAirAirport::getAirportCode,req.getAirportCode());
        MainDataAirAirport mainDataAirAirport = mainDataAirAirportMapper.selectOne(queryWrapper);
        if(null!= mainDataAirAirport&& ! req.getId().equals(mainDataAirAirport.getId())){
            return  Result.failed(SystemError.SYS_421);
        }
        MainDataAirAirport updateData = EntityUtil.copy(req,MainDataAirAirport.class);
        updateData.setGmtModified(LocalDateTime.now());
        updateData.setModifiedId(tokenUser.getId());
        updateData.setModifiedName(tokenUser.getUsername());
        mainDataAirAirportMapper.updateById(updateData);
        return Result.success(req.getId());
    }

    @Override
    public  Result importData(){
        //查询已经存在的机场三字码
        List<MainDataAirAirport> airAirportList = mainDataAirAirportMapper.selectList(new QueryWrapper<>());
        Map<String,MainDataAirAirport> airAirportMap = Maps.newHashMap();
        for (MainDataAirAirport mainDataAirAirport : airAirportList) {
            airAirportMap.put(mainDataAirAirport.getAirportCode(),mainDataAirAirport);
        }
        File excel = new File("C:\\Users\\54271\\Desktop\\work\\机票\\機場主數據.xlsx");
        Workbook wb;
        if (excel.isFile() && excel.exists()) {
            String[] split = excel.getName().split("\\.");  //.是特殊字符，需要转义！！！！！
            try {
                if ( "xls".equals(split[1])){
                    FileInputStream fis = new FileInputStream(excel);   //文件流对象
                    wb = new HSSFWorkbook(fis);
                }else if ("xlsx".equals(split[1])){
                    wb = new XSSFWorkbook(excel);
                }else {
                    System.out.println("文件类型错误!");
                    return Result.failed(SystemError.SYS_421);
                }
            }catch (Exception e){
                e.printStackTrace();
                return Result.failed(SystemError.SYS_400);
            }
            //开始解析
            Sheet sheet = wb.getSheetAt(0);     //读取sheet 0
            int firstRowIndex = sheet.getFirstRowNum()+1;   //第一行是列名，所以不读
            int lastRowIndex = sheet.getLastRowNum();
            System.out.println("firstRowIndex: "+firstRowIndex);
            System.out.println("lastRowIndex: "+lastRowIndex);
            QueryWrapper<SysArea> areaQueryWrapper = new QueryWrapper<>();
            for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {   //遍历行
                System.out.println("rIndex: " + rIndex);
                Row row = sheet.getRow(rIndex);
                if (row != null) {
                    Cell firstCell = row.getCell(0);
                    if(null==firstCell){
                        continue;
                    }
                    String code = row.getCell(1).getStringCellValue();
                    if(StringUtils.isBlank(code)){
                        continue;
                    }
                    String name = row.getCell(2).getStringCellValue();
                    String airportCode = row.getCell(3).getStringCellValue();
                    String airportName = row.getCell(4).getStringCellValue();
                    if(airAirportMap.containsKey(airportCode)){//已经存在的机场三字码 不新增
                        continue;
                    }
                    areaQueryWrapper.clear();
                    //先查询城市
                    SysArea sysArea;
                    areaQueryWrapper.lambda().eq(SysArea::getCityCode,code);
                    sysArea = sysAreaMapper.selectOne(areaQueryWrapper);
                    String cusName;
                    if(null==sysArea){//查询省份
                        areaQueryWrapper.clear();
                        areaQueryWrapper.lambda().eq(SysArea::getProvinceCode,code);
                        sysArea = sysAreaMapper.selectOne(areaQueryWrapper);
                        if(null==sysArea){
                            areaQueryWrapper.clear();
                            areaQueryWrapper.lambda().eq(SysArea::getCountryCode,code);
                            sysArea = sysAreaMapper.selectOne(areaQueryWrapper);
                        }
                    }
                    if(null==sysArea){
                        continue;
                    }
                    MainDataAirAirport mainDataAirAirport = new MainDataAirAirport();
                    mainDataAirAirport.setId(IdWorker.getId());
                    mainDataAirAirport.setGmtModified(LocalDateTime.now());
                    mainDataAirAirport.setGmtCreate(LocalDateTime.now());
                    mainDataAirAirport.setCustomId(sysArea.getId());
                    mainDataAirAirport.setCustomCode(code);
                    mainDataAirAirport.setCustomName(sysArea.getCountryTraditional());
                    mainDataAirAirport.setAirportCode(airportCode);
                    mainDataAirAirport.setAirportName(airportName);
                    mainDataAirAirport.setStatus(0);
                    mainDataAirAirportMapper.insert(mainDataAirAirport);
                    System.out.println("code:"+code+"#####name:"+name+"#####airportCode:"+airportCode+"#####airportName:"+airportName);
                }
            }
        }
        return  Result.success();
    }

//    public static void main(String[] args) throws IOException, InvalidFormatException {
//        importData("");
//    }
}
